import React, { PureComponent } from 'react'
//import Geolocation from 'Geolocation'
import { View, StyleSheet, Image, Text, ScrollView, TouchableOpacity, ListView, StatusBar, FlatList, Platform } from 'react-native'
import ScrollableTabView, { DefaultTabBar, ScrollableTabBar } from 'react-native-scrollable-tab-view'
import LinearGradient from 'react-native-linear-gradient'
import { Heading2, Title, Price } from '../../widget/Text'
import { color, Button, NavigationItem, SpacingView } from '../../widget'

import { screen, system } from '../../common'

import HomeMenuView from './HomeMenuView'
import HomeGridView from './HomeGridView'
import GroupPurchaseCell from '../GroupPurchase/GroupPurchaseCell'
import TabScene_recommend from './tab/recommend/TabScene_recommend'
import TabScene_grouppurchase from './tab/grouppurchase/TabScene_grouppurchase'
import DetailScene_GroupPurchase from './tab/grouppurchase/DetailScene_GroupPurchase'
import TabScene_phone from './tab/TabScene_phone'
import * as api from '../../api'

type Props = {
    titles: any,
    navigation: any
}

type State = {
    locationCity: string,//定位城市
    messageNum: Number,//消息数量
    //categoryList: Array<Object>,//一级分类
    allTab: Array<Object>,//需要显示的tab页
    indexTab:Number,//激活的tab页
    groupIndex:Number,//拼团的tab索引
}

class HomeScene extends PureComponent<Props, State> {

    static navigationOptions = ({ navigation }: any) => ({
        header: null,//不使用导航栏
    })

    constructor(props: Props) {
        super(props)
        this.state = {
            locationCity: "北京",//初始化定位城市为北京
            messageNum: 0,//初始化消息数为0
            // categoryList: [],
            allTab: [],
            indexTab:0,
            groupIndex:0,
        }
        if (Platform.OS !== 'ios') {
            StatusBar.setTranslucent(true)
        }

    }
    //获取当前定位
    getCurLocation = () => {
        // let navigator=this.props.navigator;
        navigator.geolocation.watchPosition(
            (position) => {
                let longitude = JSON.stringify(position.coords.longitude);//经度
                let latitude = JSON.stringify(position.coords.latitude);//纬度
                this.fetchCity(longitude, latitude);
            }
        );
    }
    // 根据经纬度信息或读取当前城市
    fetchCity = (longitude, latitude) => {
        let url = "http://api.map.baidu.com/geocoder?output=json&location=" + latitude + ',' + longitude + "&ak=esNPFDwwsXWtsQfw4NMNmur1"
        //alert(url);
        fetch(url)
            .then((response) => response.json())
            .then((responseBody) => {
                //将xx市转换为xx
                let city = responseBody.result.addressComponent.city.slice(0, -1)
                //alert(city)
                this.setState({ locationCity: city })
            }).catch((error) => {
                alert('定位失败！')
            });
    }

    // componentWillMount = () => {
    //     this.getCategoryList();
    // };

    //组件出现后
    componentDidMount = () => {
        this.getCategoryList();
        this.getCurLocation();

    };
    //前往首页搜索页面
    onPressSearch = () => {
        alert("前往搜索界面！")
    }
    //前往消息界面
    onPressMessage = () => {
        alert("前往消息界面！")
    }
    //获取一级分类
    getCategoryList = async () => {
        try {
            let json = await api.doPost("/goods/getCategoryList", {})
            this.getAllTab(json.data)
            // this.setState({
            //     categoryList: json.data
            // })

        } catch (error) {
            alert('请求失败，请重试' + error)
        }

    }

    getAllTab(categoryList: Array) {
        let allTab = []
        for (let i = 0; i < categoryList.length; ++i) {
            let tab;
            let label = categoryList[i].label
            let value = categoryList[i].value
            if ('推荐' !== label && '拼团' !== label) {

                tab = <TabScene_phone key={value} tabLabel={label} navigation={this.props.navigation} categoryId={value} />
            } else if ('推荐' == label) {
                
                tab = <TabScene_recommend
                    key={value}
                    tabLabel={label}
                    navigation={this.props.navigation}
                    onPressGroupMore={() => {
                        this.setState({
                            indexTab:2,
                        })
                        //alert(this.state.indexTab)
                    }} />
            } else {
                tab = <TabScene_grouppurchase key={value} tabLabel={label} navigation={this.props.navigation} />
                this.setState({
                    groupIndex:i,
                })
            }
            allTab.push(tab)
        }
        this.setState({
            allTab: allTab
        })
    }

    render() {
        //alert(JSON.stringify(this.state.categoryList.length)) 
        let titles = ['推荐', '手机', '拼团', '运营商套餐', '饮食', '智能潮流', '洗护', '婴童', '家居', '餐厨', '配饰'];

        return (
            <View style={styles.container}>
                <LinearGradient colors={['#FACF5B', '#FAC858', '#FBBC53', '#FBB558', '#FAAD6B', '#F9A87A', '#F9A387']}
                    start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} >
                    <View style={{height: 105, alignItems: 'flex-start'}}>
                        <View style={styles.headerTitle}>
                            <TouchableOpacity style={styles.location}>
                                <Text style={{ marginLeft: 17, marginRight: 5, fontSize: 13, color: '#595959' }}>{this.state.locationCity}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.searchBar}>
                                <Text style={{ fontSize: 10, color: '#999999', marginLeft: 17 }}>请输入搜索关键词</Text>
                                <View flex={1} />
                                <Image source={require('../../img/home/search_icon.png')} style={styles.searchIcon} />
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.messageView}>
                                <Image source={require('../../img/mine/icon_navigation_item_message_white.png')} style={styles.messageImage} />
                            </TouchableOpacity>
                        </View>
                    </View>
                    {/*
                      <Text style={{position: 'absolute', bottom: 15, right: 0, fontSize: 13}}>1234</Text>
                    <View style={{height: 80, backgroundColor: '#333', position: 'absolute', width: '100%', top: 80, zIndex: 9999}}></View>
                    
                    */}
                  
                </LinearGradient>
                
                <ScrollableTabView
                    renderTabBar={() => <ScrollableTabBar textStyle={{}} style={{height: 40, marginTop: -11, 
                        //marginRight: 40
                    }}/> }
                    style={{
                        height: 10,
                        marginTop: -40,
                        padding: 0,
                    }}
                    tabBarBackgroundColor='transparent'
                    tabBarActiveTextColor='#EE6723'
                    tabBarInactiveTextColor='#555555'
                    tabBarTextStyle={styles.tabBarText}
                    tabBarUnderlineStyle={styles.tabBarUnderline}
                    page = {this.state.indexTab}
                    onChangeTab={(obj)=>{
                        this.setState({
                            indexTab:obj.i,
                        })
                    }}
                >
                    {this.state.allTab.length > 0 && this.state.allTab}
                </ScrollableTabView>
                
            </View>
        )
    }
}


const styles = StyleSheet.create({
    //头部导航栏的样式
    headerTitle: {
        //backgroundColor: color.white,
        width: screen.width,//设置标题栏的宽度
        height: 45,//设置标题栏的高度
        //height: 85,
        justifyContent: 'center',//横轴对齐方式
        alignItems: "center",//纵轴对齐方式
        flexDirection: 'row',
        marginTop: screen.statusBarHeight,
    },
    location: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        // margin: 5,
    },
    searchBar: {
        // width: screen.width * 0.66,
        flex: 1,
        height: 23,
        borderRadius: 19,
        flexDirection: 'row',//横向
        justifyContent: 'flex-start',//横向对齐方式
        alignItems: 'center',//纵向对齐方式
        backgroundColor: 'white',
        alignSelf: 'center',
        marginLeft: 5,//设置左边的外边距
    },
    messageView: {
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center',
        marginRight: 14,
        marginLeft: 8,
    },
    messageImage: {
        width: 16,
        height: 16,
    },
    searchIcon: {
        width: 12,
        height: 12,
        marginTop: 7,
        marginRight: 7,
        marginBottom: 5,
    },
    container: {
        flex: 1,
        backgroundColor: color.paper,
    },
    tabBarText: {
        fontSize: 13,
        fontWeight: 'normal',
        marginLeft: -8,
        marginRight: -8,
    },
    tabBarUnderline: {
        height: 0,
    },
})

export default HomeScene